//
//  PNetwork.h
//  iPiano
//
//  Created by wuxinting on 16/1/13.
//  Copyright © 2016年 wuxinting. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PDefine.h"

#define D_KEY_FILE @"file"
#define D_KEY_CONTENT_TYPE (@"Content-Type")

#define D_C(_res_) (((NSHTTPURLResponse *)_res_).statusCode)

// 请求完成block
typedef void(^PNetworkCompleteHandler)(NSURLResponse *response, id responseObj, NSError *error);

// 文件下载进度
typedef void(^PNetworkProcessHandler)(NSProgress *progress);

// 文件下载的路径
typedef NSURL * (^PNetworkDestination)(NSURL *targetPath, NSURLResponse *response);

typedef NS_ENUM(NSInteger, PNetworkFileType)
{
    PNetworkFileImagePNG,
    PNetworkFileImageJPG,
    PNetworkFileImageJPEG
    // more...
};

/**
 上传文件的描述类
 */
@interface PNetworkFile : NSObject

@property (nonatomic, strong) NSURL * filePath;

// 如果给的是文件内容，需要文件名称和类型
@property (nonatomic, strong) NSData * fileData;
@property (nonatomic, copy) NSString * fileName;
@property (nonatomic, assign) PNetworkFileType fileType;

+ (instancetype)initWithFilePath:(NSURL *)filePath;
+ (instancetype)initWithFileData:(NSData *)fileData andFileName:(NSString *)fileName andType:(PNetworkFileType)type;

@end

@interface PNetwork : NSObject

DEC_SINGLETON(PNetwork)

@property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> * headers;

// 同步GET
- (NSURLResponse*)getSync:(NSURL*)url andParams:(NSDictionary*)params;

// 异步GET
- (BOOL)get:(NSURL*)url andParams:(NSDictionary*)params completionHandler:(PNetworkCompleteHandler)handler;

// 同步POST
- (NSURLResponse*)postSync:(NSURL*)url andParams:(NSDictionary*)params;

// 异步POST
- (BOOL)post:(NSURL*)url andParams:(NSDictionary*)params completionHandler:(PNetworkCompleteHandler)handler;

/**
 上传文件接口

 @param url 上传到服务器地址
 @param path 被上传文件路径
 @param params 附加参数 （不可嵌套，NSData NSURL将被附加到FILE中）
 @param progressHandler 进度回调
 @param completeHandler 完成回调
 @return 是否发起上传成功
 */
- (BOOL)upload:(NSURL*)url andFilePath:(NSURL*)path andParams:(NSDictionary*)params progressHandler:(PNetworkProcessHandler)progressHandler completionHandler:(PNetworkCompleteHandler)completeHandler;
- (BOOL)upload:(NSURL*)url withFilesAndParams:(NSDictionary*)fileAndParams progressHandler:(PNetworkProcessHandler)progressHandler completionHandler:(PNetworkCompleteHandler)completeHandler;

// 下载文件
- (BOOL)download:(NSURL*)url andParams:(NSDictionary*)params progressHandler:(PNetworkProcessHandler)progressHandler atDestination:(PNetworkDestination)destination completionHandler:(PNetworkCompleteHandler)completeHandler;

@end

typedef NSString * PNetworkParamKey;
FOUNDATION_EXPORT const PNetworkParamKey PNetworkParamKeyCache;

FOUNDATION_EXTERN const NSInteger NWErrorSuccess;
FOUNDATION_EXTERN const NSInteger NWErrorUnknown;
FOUNDATION_EXTERN const NSInteger NWErrorDoesNotExist;

FOUNDATION_EXTERN NSNotificationName const PNetWorkErrorNotification;
